package com.fs.base.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Getter;
import lombok.Setter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.base.param.SysConstant;
import com.fs.base.pojo.User;
import com.fs.base.utils.ApplicationUtils;
import com.fs.base.vo.SysPath;

/**
 * @author TiddlerCJ
 * @desc 自定义拦截器
 */
@Configuration
public class SysInterceptors  extends WebMvcConfigurerAdapter {
	@Setter @Getter 
	@Value("${sysconfig.backExcludePath}")
	private String backExcludePath;
	public void addInterceptors(InterceptorRegistry registry) {
		/*
		 * 1.session拦截处理
		 */
		HandlerInterceptor sessionInterceptor = new HandlerInterceptorAdapter() {
	          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
					String ctx = request.getContextPath();
					if ("/".equals(ctx)) ctx = "";
				  if(sessionTimeout(request)){
	      			if (request.getHeader("x-requested-with") != null && 
	      				//异步请求超时的处理
	      			    request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
	      			    PrintWriter wirter =  response.getWriter();
	      			    wirter.write("timeout"); wirter.flush(); wirter.close();
	      			}else{
	      				//普通超时处理
                        StringBuffer responseStr = new StringBuffer()  
                         		.append("<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"/plug-in/layui/css/layui.css\"/>");
                         		if(request.getRequestURI().equals("/console")){
                         			responseStr.append("<script type=\"text/javascript\">window.parent.document.location.href='")
                         			.append(SysPath.BACK_LOGIN_PATH).append("';</script></head>");
        	      				}else {
        	      					responseStr.append("<script type=\"text/javascript\" src=\"/plug-in/layui/layui.all.js\"></script></head><body style='text-align:center;background-color:#c2c2c2;'>")
                             		.append("<div style='margin-top:250;font-size : 2em;color : #535353;'>登录已过期</div>")
                             		.append("<div style='margin:10 auto;padding:10;'><a href='javascript:void(0);' class='layui-btn'  onClick=\"")
                             		.append("window.parent.document.location.href='")
                             		.append(ctx + SysPath.BACK_LOGIN_PATH).append("'\"")
                             		.append(">重新登录</a></div></body>");
								}
                         		responseStr.append("</html>");
                         response.setContentType("text/html;charset=UTF-8");
                         response.getWriter().print(responseStr);
	      			}
	      				return false;
	        	  }else{
	        		  /*
	        		   * 将当前请求菜单动作传递到页面
	        		   */
	        		  String menuId = request.getParameter("menuId");
	        		  if(StringUtils.isNotBlank(menuId)){
	        			  JSONObject menuMotions = ApplicationUtils.getMenuMotions();
	        			  JSONArray json = menuMotions.getJSONArray(menuId);
	        			  if(json==null) json = new JSONArray();
	        			  request.setAttribute(SysConstant.PARAM_MENU_MOTIONS, json);
	        		  }
	        		  return true;
	        	  }
	          }
	    };
	    
	    /*
	     * 免拦截路径
	     */
	    String[] excludePath = {};
	    if(StringUtils.isNotBlank(backExcludePath)){ excludePath = backExcludePath.split(","); }
	    
	    registry.addInterceptor(sessionInterceptor).addPathPatterns(SysPath.BACK_PATH.concat("/**"))
	    		.excludePathPatterns(SysPath.BACK_LOGIN_PATH)
	    		.excludePathPatterns(SysPath.BACK_LOGOUT_PATH)
	    		.excludePathPatterns(excludePath);
	    /*
	     * 2.异常拦截处理
	     */
	    HandlerInterceptor exceptionInterceptor = new HandlerInterceptorAdapter() {
	          public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
	        	  //TODO... Exception拦截器 
	              return true;
	          }
	    };
	    registry.addInterceptor(exceptionInterceptor);
	    
	    /*
	     * 3.日志拦截处理
	     */
	    HandlerInterceptor logInterceptor = new HandlerInterceptorAdapter() {
	    	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
	    		//TODO... Log拦截器 
	    		super.afterCompletion(request, response, handler, ex);
	    	}
	    };
	    registry.addInterceptor(logInterceptor);
	}
	
	private boolean  sessionTimeout(HttpServletRequest req){ 
		Boolean flag = false;
		User user = ApplicationUtils.User();
		if(user==null){ flag = true; }
		return flag;
	}
}
